package com.example.server.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.example.server.pojo.*;
import com.example.server.service.*;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URL;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author jobob
 * @since 2025-07-22
 */
@RestController
@RequestMapping("/employee/basic")
public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IPoliticsStatusService politicsStatusService;
    @Autowired
    private IJoblevelService jobLevelService;
    @Autowired
    private INationService nationService;
    @Autowired
    private IDepartmentService departmentService;
    @Autowired
    private IPositionService positionService;

    @ApiOperation(value = "获取所有员工(分页)")
    @GetMapping("/")
    public RespPageBean getEmployeeByPage(@RequestParam (defaultValue = "1")Integer currentPage,
                                          @RequestParam(defaultValue = "10") Integer size,
                                          Employee employee,
                                          @ApiParam(name = "beginDateScope",
                                                  value = "日期范围查询参数，格式: 2020-01-01,2025-12-31",
                                                  example = "2020-01-01,2025-12-31",
                                                  type = "array")
                                          @RequestParam(required = false) LocalDate[] beginDateScope){
        return employeeService.getEmployeeByPage(currentPage,size,employee,beginDateScope);
    }

    @ApiOperation(value = "获取所有政治面貌")
    @GetMapping("/politicsStatus")
    public List<PoliticsStatus> getAllPoliticsStatus(){
        return politicsStatusService.list();
    }

    @ApiOperation(value = "获取所有职称")
    @GetMapping("/jobLevel")
    public List<Joblevel> getAllJobLevels(){
        return jobLevelService.list();
    }

    @ApiOperation(value = "获取所有民族")
    @GetMapping("/nation")
    public List<Nation> getAllNations(){
        return nationService.list();
    }

    @ApiOperation(value = "获取所有部门")
    @GetMapping("/department")
    public List<Department> getAllDepartments(){
        return departmentService.getAllDepartments();
    }

    @ApiOperation(value = "获取所有职位")
    @GetMapping("/position")
    public List<Position> getAllPositions(){
        return positionService.list();
    }

    @ApiOperation(value = "获取最大工号")
    @GetMapping("/maxWorkID")
    public RespBean maxWorkID(){
        return employeeService.maxWorkID();
    }

    @ApiOperation(value = "添加员工")
    @PostMapping("/")
    public RespBean addEmp(@RequestBody  Employee employee){
        return employeeService.addEmp(employee);
    }

    @ApiOperation(value = "更新员工")
    @PutMapping("/")
    public RespBean updateEmp(@RequestBody Employee employee){
        if (employeeService.updateById(employee)){
            return RespBean.success("更新成功");
        }
        return RespBean.error("更新失败");
    }

    @ApiOperation(value = "删除员工")
    @DeleteMapping("/{id}")
    public RespBean deleteEmp(@PathVariable Integer id){
        if (employeeService.removeById(id)){
            return RespBean.success("删除成功");
        }
        return RespBean.error("删除失败");
    }

    @ApiOperation(value = "导出员工数据")
    @GetMapping(value = "/export", produces = "application/octet-stream")
    public void exportEmployee(HttpServletResponse response) {
        ServletOutputStream out = null;
        try {
            List<Employee> list = employeeService.getEmployee(null);
            ExportParams params = new ExportParams("员工表", "员工表", ExcelType.HSSF);
            Workbook workbook = ExcelExportUtil.exportExcel(params, Employee.class, list);

            // 设置响应头
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("utf-8");
            // 防止中文乱码
            response.setHeader("content-disposition", "attachment;filename=" +
                    URLEncoder.encode("员工表.xls", "UTF-8"));

            out = response.getOutputStream();
            workbook.write(out);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @ApiOperation(value = "导入员工数据")
    @PostMapping("/import")
    public RespBean importEmployee(@ApiParam(name = "file", value = "员工数据Excel文件", required = true)
                                       @RequestPart("file") MultipartFile file){
        ImportParams params = new ImportParams();
        //去掉标题行
        params.setTitleRows(1);
        List<Nation> nationList = nationService.list();
        List<PoliticsStatus> politicsStatusList = politicsStatusService.list();
        List<Department> departmentList = departmentService.list();
        List<Joblevel> joblevelList = jobLevelService.list();
        List<Position> positionList = positionService.list();
        // 创建映射关系提高查找效率
        Map<String, Integer> nationMap = nationList.stream()
                .collect(Collectors.toMap(Nation::getName, Nation::getId, (existing, replacement) -> existing));
        Map<String, Integer> politicsStatusMap = politicsStatusList.stream()
                .collect(Collectors.toMap(PoliticsStatus::getName, PoliticsStatus::getId, (existing, replacement) -> existing));
        Map<String, Integer> departmentMap = departmentList.stream()
                .collect(Collectors.toMap(Department::getName, Department::getId, (existing, replacement) -> existing));
        Map<String, Integer> joblevelMap = joblevelList.stream()
                .collect(Collectors.toMap(Joblevel::getName, Joblevel::getId, (existing, replacement) -> existing));
        Map<String, Integer> positionMap = positionList.stream()
                .collect(Collectors.toMap(Position::getName, Position::getId, (existing, replacement) -> existing));

        try {
            List<Employee> list = ExcelImportUtil.importExcel(file.getInputStream(), Employee.class, params);
            for (Employee employee : list) {
                // 设置民族ID
                if (employee.getNation() != null && employee.getNation().getName() != null
                        && !employee.getNation().getName().trim().isEmpty()) {
                    String nationName = employee.getNation().getName().trim();
                    if (nationMap.containsKey(nationName)) {
                        employee.setNationId(nationMap.get(nationName));
                    }
                }

                // 设置政治面貌ID
                if (employee.getPoliticsStatus() != null && employee.getPoliticsStatus().getName() != null
                        && !employee.getPoliticsStatus().getName().trim().isEmpty()) {
                    String politicsName = employee.getPoliticsStatus().getName().trim();
                    if (politicsStatusMap.containsKey(politicsName)) {
                        employee.setPoliticId(politicsStatusMap.get(politicsName));
                    }
                }

                // 设置部门ID
                if (employee.getDepartment() != null && employee.getDepartment().getName() != null
                        && !employee.getDepartment().getName().trim().isEmpty()) {
                    String departmentName = employee.getDepartment().getName().trim();
                    if (departmentMap.containsKey(departmentName)) {
                        employee.setDepartmentId(departmentMap.get(departmentName));
                    }
                }

                // 设置职称ID
                if (employee.getJobLevel() != null && employee.getJobLevel().getName() != null
                        && !employee.getJobLevel().getName().trim().isEmpty()) {
                    String joblevelName = employee.getJobLevel().getName().trim();
                    if (joblevelMap.containsKey(joblevelName)) {
                        employee.setJobLevelId(joblevelMap.get(joblevelName));
                    }
                }

                // 设置职位ID
                if (employee.getPosition() != null && employee.getPosition().getName() != null
                        && !employee.getPosition().getName().trim().isEmpty()) {
                    String positionName = employee.getPosition().getName().trim();
                    if (positionMap.containsKey(positionName)) {
                        employee.setPosId(positionMap.get(positionName));
                    }
                }
            }
            if (employeeService.saveBatch(list)){
                return RespBean.success("导入成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RespBean.error("导入失败");
    }

}
